# coding=utf-8

from flask import Blueprint, request, jsonify, json, make_response, redirect, g
from common.models.Food import Food
from common.models.Coupon import CustomerCoupon
from common.models.Order import Order, OrderItem
from common.models.Shop import Shop
from common.libs.order.OrderLibs import OrderLibs
from common.libs.Helper import get_current_time
from common.libs.UrlManager import UrlManager
from decimal import *
from application import app,db
from web.controllers.BaseControllerHelper import *
from .Helper import *

route_api_order = Blueprint( 'order_page',__name__ )

@route_api_order.route("/get_temp", methods=["POST"])
def get_temp():
    resp = gene_response(msg="OK")
    data = request.json
    info_dic = get_values_by_request(data, "info_dic")
    data_list = {}
    food_list = Food.query.filter(Food.id.in_(info_dic.keys()))
    cash = 0
    if food_list:
        temp_food_list = []
        for food in food_list:
            total = float(food.present_price * info_dic[str(food.id)])
            cash += total
            temp_data = {
                "id": food.id,
                "name": food.name,
                "image": app.config["APP"]["domain"] + "/static/upload/" + food.main_image,
                "count": info_dic[str(food.id)],
                "price": float(food.present_price),
                "total": float(total)
            }
            temp_food_list.append(temp_data)
        data_list["cash"] = float(cash)
        data_list["info_list"] = temp_food_list
        resp = gene_response(code=200, msg="OK", data=data_list)
    else:
        data_list["cash"] = float(cash)
        data_list["food_list"] = []
        resp = gene_response(code=-1, msg="暂无信息", data=data_list)
    return jsonify(resp)


@route_api_order.route("/create", methods=[ "POST"])
def create():
    resp = gene_response(msg="OK")
    data = request.json
    info_dic = get_values_by_request(data, "info_dic")
    coupon_id = get_values_by_request(data, "coupon_id")
    table_id = get_values_by_request(data, "table_id")
    shop_id = get_values_by_request(data, "shop_id")
    data_list = {}
    food_list = Food.query.filter(Food.id.in_(info_dic.keys()))
    minus_cash = 0
    if int(coupon_id) != 0 :
        minus_cash = CustomerCoupon.query.filter_by(id=int(coupon_id)).first().sc.minus_cash
    total_price = 0
    if food_list:
        for food in food_list:
            price = float(food.present_price * info_dic[str(food.id)])
            total_price += price
        try:
            order_model = Order()
            order_model.order_sn = OrderLibs.geneOrderSn()
            order_model.c_id = g.customer_info.id
            order_model.note = ""
            order_model.updated_time = get_current_time()
            order_model.created_time = get_current_time()
            order_model.shop_id = shop_id
            order_model.table_id = table_id
            order_model.meal_number = OrderLibs.geneMealNumber(table_id)
            order_model.status = 1
            order_model.total_price = 0 if float(minus_cash) > float(total_price) else (float(total_price) - float(minus_cash))
            order_model.minus_cash = float(total_price) if float(minus_cash) > float(total_price) else float(minus_cash)
            db.session.add(order_model)

            for food in food_list:
                price = float(food.present_price * info_dic[str(food.id)])
                order_item_model = OrderItem()
                order_item_model.order_id = order_model.id
                order_item_model.count = info_dic[str(food.id)]
                order_item_model.price = Decimal(str(price)).quantize(Decimal('0.00'))
                order_item_model.food_id = food.id
                order_item_model.updated_time = get_current_time()
                order_item_model.created_time = get_current_time()
                db.session.add(order_item_model)

            #优惠券设置为已使用
            if int(coupon_id) != 0 :
                db.session.query(CustomerCoupon).filter(CustomerCoupon.id==int(coupon_id)).update(
                    {'is_used': '2', 'is_valid': '2', "updated_time": get_current_time()}, synchronize_session=False)

            db.session.commit()
            data_list["is_create"] = True
            data_list["order_id"] = order_model.id
            data_list["order_sn"] = order_model.order_sn
            resp = gene_response(code=200, msg="订单创建成功", data=data_list)
        except Exception as e:
            db.session.rollback()
            data_list["is_create"] = False
            data_list["order_id"] = -1
            data_list["order_sn"] = -1
            resp = gene_response(code=-1, msg="订单创建失败", data=data_list)
    else:
        data_list["is_create"] = False
        data_list["order_id"] = -1
        data_list["order_sn"] = -1
        resp = gene_response(code=-1, msg="订单创建失败", data=data_list)
    return jsonify(resp)


@route_api_order.route("/get_one", methods=["GET"])
def get_one():
    resp = gene_response(msg="OK")
    data = request.args
    order_id = get_values_by_request(data, "order_id")
    data_list = []
    order = Order.query.filter_by(id=order_id).first()
    if order :
        temp_order_data = create_order_json(order, ["id", "order_sn", "total_price", "note", "status", "meal_number", "created_time"])
        temp_item_list = []
        for item in order.order_item :
            temp_item_data = {
                "count" : item.count,
                "price" : float(item.price),
                "food" : {
                    "name" : item.food.name,
                    "present_price" : float(item.food.present_price),
                    "image" : app.config["APP"]["domain"] + "/static/upload/" + item.food.main_image,
                }
            }
            temp_item_list.append(temp_item_data)
        temp_order_data["item"] = temp_item_list
        data_list = temp_order_data
        resp = gene_response(code=200, msg="OK", data=data_list)
    else :
        resp = gene_response(code=-1, msg="异常", data=[])
    return jsonify(resp)

@route_api_order.route("/get_my_order", methods=["GET"])
def get_my_order():
    resp = gene_response(msg="OK")
    data = request.args
    c_id = g.customer_info.id
    status = get_values_by_request(data, "status")
    shop_id = get_values_by_request(data, "shop_id")
    data_list = {}

    data_list["status"] = status
    order_list = Order.query.filter_by(shop_id=shop_id, status=status).order_by(Order.created_time.desc()).all()
    if order_list :
        temp_order_list = []
        for order in order_list :
            temp_order_data = create_order_json(order, ["id","order_sn", "created_time", "total_price"])
            temp_order_list.append(temp_order_data)
        data_list["order_list"] = temp_order_list
        resp = gene_response(code=200, msg="OK", data=data_list)
    else :
        data_list["order_list"] = []
        resp = gene_response(code=-1, msg="异常", data=data_list)
    return jsonify(resp)



